package vell.velllock.view;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import vell.velllock.R;
import vell.velllock.database.WordDBInfoOperator;
import vell.velllock.database.WordDBOperator;
import vell.velllock.object.Word;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.FontMetrics;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Vibrator;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;

@SuppressLint("ViewConstructor")
public class LockScreenView extends View {
	private Paint mPaint;
	private Context mContext;
	private Activity mParentActivity;
	// screen pixs 320 x 569
	private int mScrWidth, mScrHeight;

	private Bitmap BGImg, moveImg;
	private Bitmap[] wordBGImg = new Bitmap[2];
	
	private Word[] words;
	private int rightNum;
	
	private Point startP = new Point();
	private Point moveP = new Point();
	
	public LockScreenView(Context context, Activity parentAct) {
		super(context);
		setFocusable(true); // only this view is foucsed, onkeydown will be called.
		mContext = context;
		mParentActivity = parentAct;
		// get screen Metrics
		DisplayMetrics dm = new DisplayMetrics();
		parentAct.getWindowManager().getDefaultDisplay().getMetrics(dm);
		mScrWidth = dm.widthPixels;
		mScrHeight = dm.heightPixels;
		
		Log.i(String.valueOf(mScrWidth), String.valueOf(mScrHeight));
		mPaint = new Paint();
		// start new thread to make the screen get refreshed by every 1 second....
		
		// initialize Bitmap
		initImg();
		// initialize words and right number
		initWords();
	}
	
	@SuppressLint("NewApi")
	private void initImg(){
		Resources res = this.getResources();
		final WallpaperManager wallpaperManager = WallpaperManager.getInstance(mContext);
//		BGImg = drawableToBitmap(wallpaperManager.getDrawable());// get bitmap form wallpaper
		BGImg = BitmapFactory.decodeResource(res, R.drawable.lock_bg);
		BGImg = Bitmap.createScaledBitmap(BGImg, mScrWidth, mScrHeight, true);
		wordBGImg[0] = BitmapFactory.decodeResource(res, R.drawable.word_bg_1);
		wordBGImg[0] = Bitmap.createScaledBitmap(wordBGImg[0], mScrWidth, mScrHeight/6, true);
		wordBGImg[1] = BitmapFactory.decodeResource(res, R.drawable.word_bg_2);
		wordBGImg[1] = Bitmap.createScaledBitmap(wordBGImg[1], mScrWidth, mScrHeight/6, true);
	}
	
	public static Bitmap drawableToBitmap(Drawable drawable) {       
        Bitmap bitmap = Bitmap.createBitmap(
            drawable.getIntrinsicWidth(),
            drawable.getIntrinsicHeight(),
            drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                            : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
	}
	
	private void initWords(){
		WordDBInfoOperator WDIO = new WordDBInfoOperator(mContext);
		String DBFileName = WDIO.getActiveWordDBInfo().getDBFile();
		WordDBOperator WDO = new WordDBOperator(mContext, new File(DBFileName));
		words = WDO.getShowWords();
		//get random right number
		rightNum = (int)(words.length * Math.random());
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		// clean the screen with specific color.
		canvas.drawColor(Color.WHITE);
		mPaint.setColor(Color.WHITE);
		// 抗锯齿方法
		mPaint.setAntiAlias(true);
		
		mPaint.setTextAlign(Align.CENTER);

		// draw background
		canvas.drawBitmap(BGImg, 0, 0, mPaint);
		mPaint.setTextAlign(Align.LEFT);
		mPaint.setTextAlign(Align.CENTER);
		// draw Date text
		SimpleDateFormat eFormatter = new SimpleDateFormat("E");
		SimpleDateFormat mFormatter = new SimpleDateFormat("MM月dd日");
		SimpleDateFormat hFormatter = new SimpleDateFormat("HH:mm:ss");
		Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
		String eDate = eFormatter.format(curDate);
		String mDate = mFormatter.format(curDate);
		String hDate = hFormatter.format(curDate);
		drawText(canvas, mDate + "  " + eDate, Color.WHITE, 40 / 2,
				Typeface.DEFAULT, Align.CENTER, 90, mScrWidth/2);
		drawText(canvas, hDate, Color.WHITE, 40, Typeface.DEFAULT, Align.CENTER,
				80, mScrWidth/2);
		//draw words
		drawWordBar(canvas);
		
		this.postInvalidate();
	}
	
	public void drawWordBar(Canvas canvas){
		for(int i=0; i<words.length; i++){
			canvas.drawBitmap(wordBGImg[i], null, new Rect(0, mScrHeight*(5-i)/6, mScrWidth, mScrHeight*(6-i)/6), mPaint);
		}
	}
	
	public void drawText(Canvas canvas, String text, int color, int size,
			Typeface typeface, Align A, int h, int w) {
		mPaint.setColor(color);
		// 抗锯齿方法
		mPaint.setAntiAlias(true);
		mPaint.setTypeface(typeface);
		mPaint.setTextSize(size);
		mPaint.setTextAlign(A);

		FontMetrics fontMetrics = mPaint.getFontMetrics();
		// 计算文字高度
		float fontHeight = fontMetrics.bottom - fontMetrics.top;

		float textBaseY = h - fontHeight / 2;
		canvas.drawText(text, w, textBaseY, mPaint);
	}

	/*
	 * The first method to count unlock is that in onTouchEvent. Another method
	 * is using GestureDetector to deal with it.
	 */
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// get touched position
		int action = event.getAction();
		if (action == MotionEvent.ACTION_DOWN) {
			startP.x = (int) event.getX();
			startP.y = (int) event.getY();
		} else if (action == MotionEvent.ACTION_MOVE) {
			moveP.x = (int) event.getX();
			moveP.y = (int) event.getY();
		} else if (action == MotionEvent.ACTION_UP) {
			moveP.x = (int) event.getX();
			moveP.y = (int) event.getY();
		}

		// redraw screen
		this.postInvalidate();
		
		// check unlock
		for(int i=0; i<words.length; i++){
			
		}
/*
		for (int i = 0; i < LOCK_N; i++) {
			// 解锁是否成功
			if (movex[i] == this.mBgImage.getWidth() - LEFT_MARGIN
					- this.mSlideBtnImage[i].getWidth()
					&& mMoveValid[i] == true) {
				if (ANSWER == i) {
					DBO.saveRecordToDb(word, i, true);
					// 退出锁屏之前更新一下桌面widget
					// /////////////test//vell.AppWidgetBroadCast////////////////////
					Intent intent = new Intent();
					intent.setAction(broadCastString);
					mContext.sendBroadcast(intent);
					// /////////////test//////////////////////

					mParentActivity.finish(); // exit the process only.
				} else {
					DBO.saveRecordToDb(word, i, false);
					virbate(); // 震动一下
				}
				// System.exit(0); // exit both process and clean user data
			}
		}*/
		 return super.onTouchEvent(event);
	}

	private void virbate() {
		Vibrator vibrator = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
		vibrator.vibrate(500);
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		return super.dispatchKeyEvent(event);
	}
}
